public class MyBlockingQueue {
    private int[] arr = new int[10];//队列
    private int head;//头
    private int tail;//尾
    private int size;//已经存了几个元素
    public MyBlockingQueue(){
        head = 0;
        tail = 0;
        size = 0;
    }
    public void put(int val) throws InterruptedException {
        synchronized (this){
            if(size == arr.length){
                this.wait();//队列满了，阻塞
            }
            arr[tail] = val;
            tail = (tail+1)%arr.length;
            size++;
            this.notify();
        }
    }
    public int take() throws InterruptedException {
        synchronized (this) {
            if(size == 0){
                this.wait();//队列为空，阻塞
            }
            int tmp = arr[head];
            head = (head+1)%arr.length;
            size--;
            this.notify();
            return tmp;
        }
    }

    public static void main(String[] args){
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 13; i++) {
                try {
                    myBlockingQueue.put(i);
                    System.out.println("start:"+i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    System.out.println(myBlockingQueue.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();
    }
}
